package com.fsd.admin.service.impl;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

import javax.annotation.Resource;

import org.hibernate.Criteria;
import org.hibernate.criterion.Restrictions;
import org.springframework.stereotype.Repository;

import com.fsd.core.bean.CheckTree;
import com.fsd.core.bean.Tree;
import com.fsd.core.common.BusinessException;
import com.fsd.core.service.impl.BaseServiceImpl;
import com.fsd.core.util.Config;
import com.fsd.core.util.EhcacheUtil;
import com.fsd.core.util.ParametersUtil;
import com.fsd.admin.model.A_Employee;
import com.fsd.admin.model.Sys_PopedomAllocate;
import com.fsd.admin.model.Sys_SystemMenu;
import com.fsd.admin.model.Sys_SystemMenuPopup;
import com.fsd.admin.service.Sys_SystemMenuPopupService;
import com.fsd.admin.service.Sys_SystemMenuService;
import com.fsd.admin.service.Sys_SystemParametersService;
import com.fsd.admin.dao.Sys_PopedomAllocateDao;
import com.fsd.admin.dao.Sys_SystemMenuDao;
import com.google.gson.Gson;

@Repository("Sys_SystemMenuServiceImpl")
public class Sys_SystemMenuServiceImpl extends MainServiceImpl<Sys_SystemMenu, String> implements Sys_SystemMenuService{
    
	private String depict = "菜单";
	
    @Resource(name = "Sys_SystemMenuDaoImpl")
	public void setBaseDao(Sys_SystemMenuDao Sys_SystemMenuDao) {
		super.setBaseDao(Sys_SystemMenuDao);
	}
	
	@Resource(name = "Sys_SystemMenuDaoImpl")
	private Sys_SystemMenuDao objectDao;
	
	@Resource(name = "Sys_PopedomAllocateDaoImpl")
	private Sys_PopedomAllocateDao popedomDao;
	
	@Resource(name = "Sys_SystemParametersServiceImpl")
	private Sys_SystemParametersService sysParametersService;
	
	@Resource(name = "Sys_SystemMenuPopupServiceImpl")
   	private Sys_SystemMenuPopupService MenuPopupService;
	
	private static final Lock lock = new ReentrantLock();
	/**
	 * 菜单递回创建
	 * @param menu
	 * @param menuList
	 */
	private void getMenuStruct(Sys_SystemMenu menu, List<Sys_SystemMenu> menuList){
		for (Sys_SystemMenu obj : menuList) {
			if(menu.getCode().equals(obj.getParentcode())){
				menu.getList().add(obj);
				this.getMenuStruct(obj, menuList);
			}
		}
	}
	/**
	 * 获取菜单权限
	 * @param code
	 * @return
	 */
	public Sys_SystemMenu getMenuStructByCode(String code, String companyid){
		lock.lock();
		Map<String, Sys_SystemMenu> menuMap = null;
		String strKey = Config.MENUMAP + companyid;
		try {
			if(EhcacheUtil.getInstance().get(strKey) == null){
				List<Sys_SystemMenu> allMenuList = objectDao.queryByHql(
						"from Sys_SystemMenu t where t.companyid = '" + companyid + "' order by t.sort");
				menuMap = new HashMap<String, Sys_SystemMenu>();
				List<Sys_SystemMenu> menuList = new ArrayList<Sys_SystemMenu>();
				List<Sys_SystemMenu> mList = new ArrayList<Sys_SystemMenu>();
				for (Sys_SystemMenu obj : allMenuList) {
					menuMap.put(obj.getCode(), obj);
					if("0".equals(obj.getParentcode())){
						mList.add(obj);
					}else{
						menuList.add(obj);
					}
				}
				for (Sys_SystemMenu obj : mList) {
					this.getMenuStruct(obj, menuList);
				}
				EhcacheUtil.getInstance().put(strKey , menuMap);
			}else{
				menuMap = (Map<String, Sys_SystemMenu>)EhcacheUtil.getInstance().get(strKey);
			}
		} finally {
			lock.unlock();
		}
		if (menuMap != null && menuMap.containsKey(code))
			return menuMap.get(code);
		else
			return null;
	}
	
	
	
	
	/**
	 * 获取用户菜单
	 * @param user
	 * @return
	 */
	public List<Tree> getUserMenu(A_Employee user, List<String> popedomList) throws Exception{
		List<Tree> menulist = new ArrayList<Tree>();
		//String menuKey = sysParametersService.getParameterValueByCode(Config.SITEMENU, user.getCompanyid());
		List<Object> list = this.getMenuStructByCode("main", "gsst").getList();
		if (list == null || list.size() == 0)
			return menulist;
		Tree tree = null;
		Sys_SystemMenu menu = null;
		for (Object object : list) {
			menu = (Sys_SystemMenu) object;
			if ("true".equals(menu.getIsuse()) && "true".equals(menu.getIsshow())){
				if (!user.isIsadmin())
				{
					if ("true".equals(menu.getIspopedom())){
						//判断是否有权限
						if (popedomList.indexOf(menu.getCode()) == -1)
							continue;
					}
				}
				tree = new Tree();
				tree.setId(menu.getCode());
				tree.setText(menu.getShowname());
				tree.setIcon(menu.getIconpath());
				tree.setModule(menu.getFormname());
				tree.setIsDialog(menu.getIsdialog());
				this.getTreeStruct(popedomList, user.isIsadmin(), tree, menu.getList());
				menulist.add(tree);
			}
		}
		return menulist;
	}
	
	/**
	 * 获取带复选框的用户菜单
	 * @param user
	 * @return
	 */
	public List<CheckTree> getUserCheckMenu(A_Employee user, List<String> popedomList) throws Exception{
		List<Sys_SystemMenuPopup> kjcdlist = MenuPopupService.getObjectListByEmployeeid(user.getId());
		List<CheckTree> menulist = new ArrayList<CheckTree>();
		//String menuKey = sysParametersService.getParameterValueByCode(Config.SITEMENU, user.getCompanyid());
		List<Object> list = this.getMenuStructByCode("main", "gsst").getList();
		if (list == null || list.size() == 0)
			return menulist;
		CheckTree tree = null;
		Sys_SystemMenu menu = null;
		for (Object object : list) {
			menu = (Sys_SystemMenu) object;
			if ("true".equals(menu.getIsuse()) && "true".equals(menu.getIsshow())){
				if (!user.isIsadmin())
				{
					if ("true".equals(menu.getIspopedom())){
						//判断是否有权限
						if (popedomList.indexOf(menu.getCode()) == -1)
							continue;
					}
				}
				
				tree = new CheckTree();
				tree.setId(menu.getCode());
				tree.setText(menu.getShowname());
				tree.setIcon(menu.getIconpath());
				tree.setModule(menu.getFormname());
				tree.setIsDialog(menu.getIsdialog());
				for (int i = 0; i < kjcdlist.size(); i++) {
					if(menu.getCode().equals(kjcdlist.get(i).getMenucode())){
						tree.setChecked(true);
					}
				}
				this.getCheckTreeStruct(popedomList, user.isIsadmin(), tree, menu.getList(), kjcdlist);
				menulist.add(tree);
			}
		}		
		return menulist;
	}
	
	/**
	 * 获得菜单结构
	 * @param isAdmin
	 * @param fTree
	 * @param list
	 */
	private void getTreeStruct(List<String>popedomList, Boolean isAdmin, Tree fTree, List<Object> list){
		fTree.setLeaf(true);
		if (list == null && list.size() == 0){
			return;
		}
		Tree tree = null;
		Sys_SystemMenu menu = null;
		for (Object object : list) {
			menu = (Sys_SystemMenu) object;
			if ("true".equals(menu.getIsuse()) && "true".equals(menu.getIsshow())){
				if (!isAdmin)
				{
					if ("true".equals(menu.getIspopedom())){
						//判断是否有权限
						if (popedomList.indexOf(menu.getCode()) == -1)
							continue;
					}
				}
				fTree.setLeaf(false);
				tree = new Tree();
				tree.setId(menu.getCode());
				tree.setText(menu.getShowname());
				tree.setIcon(menu.getIconpath());
				tree.setModule(menu.getFormname());
				tree.setIsDialog(menu.getIsdialog());
				this.getTreeStruct(popedomList, isAdmin, tree, menu.getList());
				fTree.getChildren().add(tree);
			}
		}
	}
	
	
	/**
	 * 获得复选菜单结构
	 * @param isAdmin
	 * @param fTree
	 * @param list
	 */
	private void getCheckTreeStruct(List<String>popedomList, Boolean isAdmin, CheckTree fTree, List<Object> list, List<Sys_SystemMenuPopup> kjcdlist){
		fTree.setLeaf(true);
		if (list == null && list.size() == 0){
			return;
		}
		CheckTree tree = null;
		Sys_SystemMenu menu = null;
		for (Object object : list) {
			menu = (Sys_SystemMenu) object;
			if ("true".equals(menu.getIsuse()) && "true".equals(menu.getIsshow())){
				if (!isAdmin)
				{
					if ("true".equals(menu.getIspopedom())){
						//判断是否有权限
						if (popedomList.indexOf(menu.getCode()) == -1)
							continue;
					}
				}
				fTree.setLeaf(false);
				tree = new CheckTree();
				tree.setId(menu.getCode());
				tree.setText(menu.getShowname());
				tree.setIcon(menu.getIconpath());
				tree.setModule(menu.getFormname());
				tree.setIsDialog(menu.getIsdialog());
				for (int i = 0; i < kjcdlist.size(); i++) {
					if(menu.getCode().equals(kjcdlist.get(i).getMenucode())){
						tree.setChecked(true);
					}
				}
				this.getCheckTreeStruct(popedomList, isAdmin, tree, menu.getList(), kjcdlist);
				fTree.getChildren().add(tree);
			}
		}
	}
	
	
	
	/**
	 * 获取权限树
	 * @param user
	 * @return
	 */
	public List<CheckTree> getAllQxMenuCheck(ParametersUtil parameters, A_Employee employee) throws Exception{
		//String menuKey = sysParametersService.getParameterValueByCode(Config.SITEMENU, employee.getCompanyid());
		String menuKey = "gsst";
		List<CheckTree> menulist = new ArrayList<CheckTree>();
		List<Object> list = this.getMenuStructByCode("main", menuKey).getList();
		if (list == null || list.size() == 0)
			return menulist;
		CheckTree tree = null;
		Sys_SystemMenu menu = null;
		for (Object object : list) {
			menu = (Sys_SystemMenu) object;
			if ("true".equals(menu.getIsuse())){
				tree = new CheckTree();
				tree.setChecked(false);
				tree.setId(menu.getCode());
				tree.setText(menu.getShowname());
				tree.setIcon(menu.getIconpath());
				tree.setModule(menu.getFormname());
				tree.setIsDialog(menu.getIsdialog());
				this.getCheckTreeStruct(tree, menu.getList());
				menulist.add(tree);
			}
		}
		return menulist;
	}
	/**
	 * 获得复选框权限结构
	 * @param isAdmin
	 * @param fTree
	 * @param list
	 */
	private void getCheckTreeStruct(CheckTree fTree, List<Object> list){
		fTree.setLeaf(true);
		if (list == null && list.size() == 0){
			return;
		}
		CheckTree tree = null;
		Sys_SystemMenu menu = null;
		for (Object object : list) {
			menu = (Sys_SystemMenu) object;
			if ("true".equals(menu.getIsuse())){
				fTree.setLeaf(false);
				tree = new CheckTree();
				tree.setChecked(false);
				tree.setId(menu.getCode());
				tree.setText(menu.getShowname());
				tree.setIcon(menu.getIconpath());
				tree.setModule(menu.getFormname());
				tree.setIsDialog(menu.getIsdialog());
				this.getCheckTreeStruct(tree , menu.getList());
				fTree.getChildren().add(tree);
			}
		}
	}
	
	/**
	 * 获取权限树根据角色权限加载
	 * @param user
	 * @return
	 */
	public List<CheckTree> getAllQxMenuByGroup(ParametersUtil parameters, A_Employee employee) throws Exception{
		Gson gs = new Gson();
		Map objectMap = gs.fromJson(parameters.getJsonData(), Map.class);
		if(objectMap.get("id") == null && "".equals(objectMap.get("id"))){
			throw new BusinessException(depict + "获取缺少ID参数!");
		}
		List<String> popedomList = new ArrayList<String>();
		List<Sys_PopedomAllocate> allPopedomList = popedomDao.queryByHql("from Sys_PopedomAllocate t where t.belongid = '" + objectMap.get("id") + "'");
		for (Sys_PopedomAllocate obj : allPopedomList) {
			if (popedomList.indexOf(obj.getPopedomid()) == -1){
				popedomList.add(obj.getPopedomid());
			}
		}

		String menuKey = sysParametersService.getParameterValueByCode(Config.SITEMENU, employee.getCompanyid());
		List<CheckTree> menulist = new ArrayList<CheckTree>();
		List<Object> list = this.getMenuStructByCode("main", menuKey).getList();
		if (list == null || list.size() == 0)
			return menulist;
		CheckTree tree = null;
		Sys_SystemMenu menu = null;
		for (Object object : list) {
			menu = (Sys_SystemMenu) object;
			if ("true".equals(menu.getIsuse())){
				tree = new CheckTree();
				//判断是否有权限设置复选框选中
				if (popedomList.indexOf(menu.getCode()) == -1){
					tree.setChecked(false);
				}else{
					tree.setChecked(true);
				}
				tree.setId(menu.getCode());
				tree.setText(menu.getShowname());
				tree.setIcon(menu.getIconpath());
				tree.setModule(menu.getFormname());
				tree.setIsDialog(menu.getIsdialog());
				this.getCheckTreeStruct(popedomList , tree, menu.getList());
				menulist.add(tree);
			}
		}
		return menulist;
	}
	/**
	 * 获得复选框菜单结构
	 * @param isAdmin
	 * @param fTree
	 * @param list
	 */
	private void getCheckTreeStruct(List<String> popedomList , CheckTree fTree, List<Object> list){
		fTree.setLeaf(true);
		if (list == null && list.size() == 0){
			return;
		}
		CheckTree tree = null;
		Sys_SystemMenu menu = null;
		for (Object object : list) {
			menu = (Sys_SystemMenu) object;
			if ("true".equals(menu.getIsuse())){
				fTree.setLeaf(false);
				tree = new CheckTree();
				//判断是否有权限设置复选框选中
				if (popedomList.indexOf(menu.getCode()) == -1){
					tree.setChecked(false);
				}else{
					tree.setChecked(true);
				}
				tree.setId(menu.getCode());
				tree.setText(menu.getShowname());
				tree.setIcon(menu.getIconpath());
				tree.setModule(menu.getFormname());
				tree.setIsDialog(menu.getIsdialog());
				this.getCheckTreeStruct(popedomList , tree , menu.getList());
				fTree.getChildren().add(tree);
			}
		}
	}
	
	/**
	 * 获得用户的快捷菜单
	 * @param Employeeid
	 * @return
	 * @throws Exception
	 */
	public List<Sys_SystemMenu> getKjMenu(String Employeeid) throws Exception{
		List<Sys_SystemMenuPopup> list = MenuPopupService.getObjectListByEmployeeid(Employeeid);
		String[] ids = new String[list.size()];
		for (int i = 0; i < list.size(); i++) {
			ids[i] = list.get(i).getMenucode();
		}
		Criteria criteria = objectDao.createCriteria();
		criteria.add(Restrictions.in("code", ids));
		return objectDao.getList(criteria);
	}
}
